package frame.interceptor;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;





import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import frame.exception.FrameException;

/**
 * 这个类相当于try{}catch(){}的catch部分。只在有异常发生时resolveException
 * 方法才被执行。这个类要做的事情为：1，将异常信息写到日志文件。2，识别某些异常信息，生成
 * 相应的ModelAndView返回。
 * 
 * @author MR.CUIPENG
 *
 */
public class FrameExceptionHandler implements HandlerExceptionResolver{

	private Logger logger = Logger.getLogger(getClass());
	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object obj, Exception exp) {
		
		ModelAndView mv=new ModelAndView();
		if (exp instanceof FrameException){
			logger.error("有异常被拦截到", exp);
		}
		if(request.getHeader("X-Requested-With")==null){//非异步请求
			mv.setViewName("frame/errorPage");
			return mv;
		}else{//异步请求
			//配套ModelAndView 返回json数据的 json view
			MappingJacksonJsonView view = new MappingJacksonJsonView();
			Map<String, Object> attributes = new HashMap<String, Object>();
			List<String> rp=new ArrayList<String>();
			
			//主键冲突异常 DuplicateKeyException.class.equals(exp.getCause().getClass()) 提示新增失败
			if( DuplicateKeyException.class.equals(exp.getCause().getClass())){
				rp.add(exp.getCause().getCause().getMessage());
				attributes.put("msg", "FSE0007");
				attributes.put("replacer", rp);
			}else{
				attributes.put("msg", "FSE0000");
			}
			
	        view.setAttributesMap(attributes);
	        mv.setView(view);
			return mv;
		}
	}

}
